package net.kleinhenz.norabase.client.datasource;

import com.google.gwt.core.client.GWT;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.smartgwt.client.data.DSRequest;
import com.smartgwt.client.data.DSResponse;
import com.smartgwt.client.data.DataSourceField;
import com.smartgwt.client.data.fields.DataSourceIntegerField;
import com.smartgwt.client.data.fields.DataSourceTextField;
import com.smartgwt.client.rpc.RPCResponse;
import com.smartgwt.client.widgets.grid.ListGridRecord;

import java.util.List;
import java.util.Map;

import net.kleinhenz.norabase.shared.SortOrientation;
import net.kleinhenz.norabase.shared.TextMatchStyle;
import net.kleinhenz.norabase.shared.model.Rune;
import net.kleinhenz.norabase.shared.model.Spell;

public class SpellDS extends RuneDS {

    public SpellDS () {

    	super();
    	
    	// add fields taht extends the fieldset in RuneDS
        DataSourceField field;
        field = new DataSourceTextField ("desc", "Description");
        field.setRequired(true);
        field.setCanEdit(false);
        addField(field);        

        field = new DataSourceIntegerField ("cooldown", "Cooldown");
        field.setRequired(true);
        field.setCanEdit(false);
        addField(field);        
    }

    @SuppressWarnings("unchecked")
	@Override
    protected void executeFetch (final String requestId, final DSRequest request, final DSResponse response) {

    	// aquiring meta data
    	final Map<String, SortOrientation> sortSpec = convertSortSpecifier(request.getSortBy());
        final int startIndex = (request.getStartRow() < 0)?0:request.getStartRow();
        final int endIndex = (request.getEndRow() == null)?-1:request.getEndRow();
        final TextMatchStyle textMatchStyle = convertTextMatchStyle(request.getTextMatchStyle());
        final Map<String, Object> criteria = request.getCriteria().getValues();
        
        // server connection
        SpellDSServiceAsync service = GWT.create (SpellDSService.class);
        service.fetch(startIndex, endIndex, sortSpec, textMatchStyle, criteria,
        		new AsyncCallback<List<Spell>>() {
            public void onFailure(Throwable caught) {
                response.setStatus(RPCResponse.STATUS_FAILURE);
                processResponse(requestId, response);
            }
            public void onSuccess(List<Spell> result) {
                ListGridRecord[] list = new ListGridRecord[result.size()];
                if (result.size() > 0) {
                    for (int i = 0; i < result.size(); i++) {
                        ListGridRecord record = new ListGridRecord ();
                        copyValues(result.get (i), record);
                        list[i] = record;
                    }
                }
                response.setData(list);
                // IMPORTANT: for paging to work we have to specify size of full result set
                response.setTotalRows(result.size ());
                processResponse(requestId, response);
            }
        });
    }
    
    @Override
    protected void executeUpdate (final String requestId, final DSRequest request, final DSResponse response) {

    	ListGridRecord rec = getEditedRecord(request);
        Spell testRec = new Spell();
        copyValues(rec, testRec);
        SpellDSServiceAsync service = GWT.create (SpellDSService.class);
        service.update (testRec, new AsyncCallback<Spell> () {
            public void onFailure (Throwable caught) {
                response.setStatus (RPCResponse.STATUS_FAILURE);
                processResponse (requestId, response);
            }
            public void onSuccess (Spell result) {
                ListGridRecord[] list = new ListGridRecord[1];
                ListGridRecord updRec = new ListGridRecord ();
                copyValues (result, updRec);
                list[0] = updRec;
                response.setData (list);
                processResponse (requestId, response);
            }
        });
    }

    @Override
	protected void copyValues(Rune from, ListGridRecord to) {

		super.copyValues(from, to);

		Spell fromC = (Spell)from;
		to.setAttribute("desc", fromC.getDesc());
		to.setAttribute("cooldown", fromC.getCooldown());
    }
}
